package com.example.campuslink.commen.core

import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.fragment.app.DialogFragment
import androidx.viewbinding.ViewBinding
import com.example.campuslink.R

abstract class CoreDialog<VB : ViewBinding>(@LayoutRes private val layoutRes: Int) : DialogFragment()  {
    private var _binding: VB? = null
    protected val binding: VB get() = _binding!!


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NO_TITLE, R.style.Theme_CampusLink_Dialog)

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupViews()
    }

    abstract fun  setupViews()
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = createBinding(inflater, container)
        return binding.root
    }

    abstract fun createBinding(inflater: LayoutInflater, container: ViewGroup?): VB

    override fun onStart() {
        super.onStart()
        handlerOnStart()
    }

    override fun onDestroy() {
        _binding = null
        super.onDestroy()
    }

    protected open fun handlerOnStart() {
        try {
            dialog?.run {
                setCanceledOnTouchOutside(false)
                setCancelable(false)
                window?.let { window ->
                    if (!requireActivity().isFinishing) {
                        window.setGravity(Gravity.BOTTOM)
                        window.decorView.setPadding(0, 0, 0, 0)
                        window.setLayout(
                            ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT
                        )
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}